package yf.mall.controller.api.app;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUserId;
import com.yf.response.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import yf.mall.entity.*;
import yf.mall.entity.custom.KolOrderStatMap;
import yf.mall.entity.custom.KolProductParam;
import yf.mall.enums.KolProductRecommendEnum;
import yf.mall.enums.YesNoEnum;
import yf.mall.enums.app.AppBehaviorTypeEnum;
import yf.mall.enums.app.AppCourseHotEnum;
import yf.mall.service.app.*;
import yf.mall.utils.app.AppUtil;
import yf.mall.component.app.AppOrderComponent;
import yf.mall.enums.BannerTypeEnum;
import yf.mall.enums.PlatformEnum;
import yf.mall.service.BannerService;
import yf.mall.vo.app.common.ListQuery;
import yf.mall.vo.app.common.ListResult;
import yf.mall.vo.app.course.AppCourseVo;
import yf.mall.vo.app.index.AppIndexVo;
import yf.mall.vo.app.index.ExampleGoodVo;
import yf.mall.vo.app.index.FunctionAreaVo;
import yf.mall.vo.app.order.KolOrderStatVo;
import yf.mall.vo.app.order.KolOrderVo;
import yf.mall.vo.app.order.UserKolOrderStatVo;
import yf.mall.vo.app.order.UserStatListVO;
import yf.mall.vo.app.request.BehaviorRequest;
import yf.mall.vo.app.request.DailyStatisticsRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/api/app/mini/index")
public class ApiAppIndexController extends ApiAppBaseController {

    @Resource
    private AppBehaviorService appBehaviorService;

    @Resource
    private BannerService bannerService;

    @Value("${Qiniu.img_domain}")
    private String domain;

    @Resource
    private AppConfigService appConfigService;

    @Resource
    private AppOrderComponent appOrderComponent;

    @Resource
    private KolOrderStatService kolOrderStatService;

    @Resource
    private DyAccountAuthService dyAccountAuthService;

    @Resource
    private KolProductService kolProductService;


    @RequestMapping("/banner/{platform}")
    @IgnoreAuth
    public R banner(@PathVariable Integer platform) {
        Integer type = BannerTypeEnum.TOPCENTER.getIndex();
        if (platform.equals(PlatformEnum.APP.getIndex())) {
            type = BannerTypeEnum.TOPBOTTOMONE.getIndex();
        }
        BannerEntity banner = bannerService.findByType(type).get(0);
        return R.ok(domain + banner.getImg());
    }


    @RequestMapping("/index-content")
    @IgnoreAuth
    public R appIndex() {
        AppIndexVo appIndexVo = new AppIndexVo();
        List<ExampleGoodVo> goods = getExampleGoods();
        appIndexVo.setExampleGoods(goods);
        List<FunctionAreaVo> areas = JSON.parseArray(getFunctionArea(), FunctionAreaVo.class);
        appIndexVo.setFunctionArea(areas);
        List<AppCourseVo> courseVos = appCourseService.findByHot(AppCourseHotEnum.YES.getIndex());
        appIndexVo.setCourseVos(courseVos);
        List<BannerEntity> bannerEntityList = bannerService.findByType(BannerTypeEnum.TOPBOTTOMONE.getIndex());
        if (CollectionUtils.isNotEmpty(bannerEntityList)) {
            BannerEntity banner = bannerEntityList.get(0);
            appIndexVo.setTopPictrue(domain + banner.getImg());
        } else {
            appIndexVo.setTopPictrue("");
        }
        return R.ok(appIndexVo);
    }

    @Resource
    private AppCourseService appCourseService;

    @RequestMapping(value = "/ad-material",
            produces = {"application/json"},
            method = RequestMethod.POST)
    @IgnoreAuth
    public R indexAdMaterial() {
        List<BannerEntity> bannerEntityList = bannerService.findByType(BannerTypeEnum.TOPCENTER.getIndex());
        if (CollectionUtils.isNotEmpty(bannerEntityList)) {
            List<String> imgs = bannerEntityList.stream().map(banner -> domain + banner.getImg()).collect(Collectors.toList());
            return dataResult(imgs);
        }
        return dataResult(Collections.emptyList());
    }


    @RequestMapping(value = "/kol/order/dailystat",
            method = RequestMethod.POST)
    public R indexKolOrderDailyStat(@LoginUserId Long userId, @RequestBody ListQuery listQuery) {
        Integer begin = AppUtil.getIntegerDate(listQuery.getBegin());
        Integer end = AppUtil.getIntegerDate(listQuery.getBegin());

        UserStatListVO userStatListVO = new UserStatListVO();

        DyAccountAuthEntity authEntity = dyAccountAuthService.getMasterAuthByUserId(userId);
        if (authEntity != null) {
            KolOrderStatEntity query = new KolOrderStatEntity();
            query.setOpenId(authEntity.getOpenId());
            List<KolOrderStatEntity> currentUserStatEnties = kolOrderStatService.findOrderStatByOpenIds(Arrays.asList(authEntity.getOpenId()), begin, end, null, 30);
            BigDecimal currentUserPayAmount = BigDecimal.ZERO;
            if (!currentUserStatEnties.isEmpty()) {
                currentUserPayAmount = currentUserStatEnties.stream().map(KolOrderStatEntity::getTotalPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            userStatListVO.setCurrentUserStat(convertUserStat(authEntity, begin, currentUserPayAmount));
        }
        List<KolOrderStatMap> topPayAmountOrderStat = kolOrderStatService.findTopPayAmountOrderStat(begin, end, 10);
        if (topPayAmountOrderStat.isEmpty()) {
            userStatListVO.setKolOrderMonthStatList(Collections.emptyList());
            return dataResult(userStatListVO);
        }
        List<String> openIds = topPayAmountOrderStat.stream().map(KolOrderStatMap::getOpenId).collect(Collectors.toList());
        List<DyAccountAuthEntity> authInfos = dyAccountAuthService.getAuthByOpenIds(openIds);
        Map<String, DyAccountAuthEntity> authEntityMap = authInfos.stream().collect(Collectors.toMap(DyAccountAuthEntity::getOpenId, Function.identity(), (a, b) -> a));
        List<UserKolOrderStatVo> rankList = topPayAmountOrderStat.stream().map(entity -> convertUserStat(authEntityMap.get(entity.getOpenId()), begin, entity.getTotalPayAmount())).filter(Objects::nonNull).collect(Collectors.toList());
        userStatListVO.setKolOrderMonthStatList(rankList);
        return dataResult(userStatListVO);
    }

    @RequestMapping(value = "/kol/order/monthstat",
            method = RequestMethod.POST)
    public R indexKolOrderMonthStat(@LoginUserId Long userId, @RequestBody ListQuery listQuery) {
        Integer begin = AppUtil.getIntegerDate(listQuery.getBegin());
        Integer end = AppUtil.getIntegerDate(listQuery.getEnd());

        UserStatListVO userStatListVO = new UserStatListVO();

        DyAccountAuthEntity authEntity = dyAccountAuthService.getMasterAuthByUserId(userId);
        if (authEntity != null) {
            KolOrderStatEntity query = new KolOrderStatEntity();
            query.setOpenId(authEntity.getOpenId());
            List<KolOrderStatEntity> currentUserStatEnties = kolOrderStatService.findOrderStatByOpenIds(Arrays.asList(authEntity.getOpenId()), begin, end, null, 30);
            BigDecimal currentUserPayAmount = BigDecimal.ZERO;
            if (!currentUserStatEnties.isEmpty()) {
                currentUserPayAmount = currentUserStatEnties.stream().map(KolOrderStatEntity::getTotalPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            userStatListVO.setCurrentUserStat(convertUserStat(authEntity, begin, currentUserPayAmount));
        }
        List<KolOrderStatMap> topPayAmountOrderStat = kolOrderStatService.findTopPayAmountOrderStat(begin, end, 10);
        if (topPayAmountOrderStat.isEmpty()) {
            userStatListVO.setKolOrderMonthStatList(Collections.emptyList());
            return dataResult(userStatListVO);
        }
        List<String> openIds = topPayAmountOrderStat.stream().map(KolOrderStatMap::getOpenId).collect(Collectors.toList());
        List<DyAccountAuthEntity> authInfos = dyAccountAuthService.getAuthByOpenIds(openIds);
        Map<String, DyAccountAuthEntity> authEntityMap = authInfos.stream().collect(Collectors.toMap(DyAccountAuthEntity::getOpenId, Function.identity(), (a, b) -> a));
        List<UserKolOrderStatVo> rankList = topPayAmountOrderStat.stream().map(entity -> convertUserStat(authEntityMap.get(entity.getOpenId()), begin, entity.getTotalPayAmount())).filter(Objects::nonNull).collect(Collectors.toList());
        userStatListVO.setKolOrderMonthStatList(rankList);
        return dataResult(userStatListVO);
    }

    private UserKolOrderStatVo convertUserStat(DyAccountAuthEntity authEntity, Integer date, BigDecimal totalPayAmount) {
        if (authEntity == null) {
            return null;
        }
        UserKolOrderStatVo currentUserStat = new UserKolOrderStatVo();
        currentUserStat.setCityName("长沙");
        currentUserStat.setKolUserId(authEntity.getUserId());
        currentUserStat.setWxAvatar(authEntity.getAvatar());
        currentUserStat.setWxNickName(authEntity.getName());
        currentUserStat.setProductTypeName("通用");
        currentUserStat.setDateCode(date);
        currentUserStat.setTotalPayAmount(totalPayAmount != null ? totalPayAmount.toString() : "");
        return currentUserStat;
    }


    @IgnoreAuth
    @RequestMapping(value = "/order/list",
            method = RequestMethod.POST)
    public R indexOrderList(HttpServletRequest request, @RequestBody DailyStatisticsRequest listQuery) {
        Long userId = getLoginUser(request);
        log.info("用户{}获取首页订单数据，query={}", userId, listQuery);
        if (userId == null) {
            List<AppConfigEntity> appConfigEntities = appConfigService.findConfigByKey(Arrays.asList("indexExampleOrders"));
            String exampleString;
            if (appConfigEntities.isEmpty()) {
                exampleString = "[{\"pid\":\"3622599469524202646\",\"title\":\"示例订单1\",\"cover\":\"https://p6-aio.ecombdimg.com/obj/ecom-shop-material/RcqYangl_m_1bcff7dccc75a018a3fd84d23e171f64_sx_942718_www800-800\",\"kolCosRatio\":10,\"kolCosFee\":8.4,\"totalPayAmount\":84,\"paySuccessTime\":\"2023-07-31 9:04:05\",\"flowPoint\":\"PAY_SUCC\",\"flowPointStr\":\"支付成功\"}]";
            } else {
                exampleString = appConfigEntities.get(0).getValue();
            }
            return jsonDataResult(exampleString);
        }
        Map auths = null;
        if (userId != null && listQuery.getPage() == 1) { //首次加载 加载用户的头像
            auths = dyAccountAuthService.getAllAuthByUser(userId).stream().collect(Collectors.toMap(DyAccountAuthEntity::getOpenId, Function.identity()));
        }
        if (listQuery.getType() != null) {
            listQuery.setBegin(AppUtil.getBeginByType(listQuery.getType()));
            listQuery.setEnd(AppUtil.getEndByType(listQuery.getType()));
        }
        ListResult<KolOrderVo> kolOrderList = appOrderComponent.getKolOrderList(listQuery, userId);
        return dataResult(kolOrderList.getData()).putExtra("auths", auths);
    }


    @IgnoreAuth
    @RequestMapping(value = "/order/stat",
            method = RequestMethod.POST)
    public R indexOrderStat(HttpServletRequest request, @RequestBody DailyStatisticsRequest dailyStatisticsRequest) {
        Long userId = getLoginUser(request);
        KolOrderStatVo kolOrderStatVo = appOrderComponent.calKolOrderStatByUser(userId, dailyStatisticsRequest);
        return dataResult(kolOrderStatVo);

    }

    /**
     * 投诉反馈
     *
     * @return
     */
    @IgnoreAuth
    @RequestMapping(value = "/complaints",
            method = RequestMethod.POST)
    public R complaints(@RequestBody BehaviorRequest request) {
        String phone = request.getPhone();
        String title = request.getTitle();
        String content = request.getContent();
        String format = "用户%s发起投诉反馈，标题：%s；内容：%s";
        appBehaviorService.record(1L, 1L, AppBehaviorTypeEnum.COMPLAINTS.getKey(), String.format(format, phone, title, content), 10);
        return R.ok();
    }


    private String getFunctionArea() {
        List<AppConfigEntity> configList = appConfigService.findConfigByKey(Arrays.asList("appFunctionAreaJson"));
        if (configList.isEmpty()) {
            return "";
        }
        return configList.get(0).getValue();
    }

    private List<ExampleGoodVo> getExampleGoods() {
        KolProductParam param = new KolProductParam();
        param.setPageNumber(1);
        param.setPageSize(4);
        param.setOrderBy("sales desc");
        param.setRecommend(YesNoEnum.yes.getIndex());
        PageInfo<KolProductEntity> page = kolProductService.page(param);
        return page.getList().stream().map(entity -> {
            ExampleGoodVo exampleGoodVo = new ExampleGoodVo();
            exampleGoodVo.setpid(entity.getId().toString());
            exampleGoodVo.setPrice(entity.getPrice().toString());
            exampleGoodVo.setCover(entity.getCover());
            exampleGoodVo.setTitle(entity.getTitle());
            return exampleGoodVo;
        }).collect(Collectors.toList());
    }

}
